17
Build Your Own Game—Tic Tac Toe
17
squares, but were restricted to using only three pieces, so had to move them around.
Also found at Egyptian ruins, there is little doubt that this game has been popular in
history. Tic Tac Toe has many names in other countries—it is called “Kata Kuti” in
the Eastern part of India, “Exy-Ozies” in Ireland, and “Xs and Os” in Zimbabwe!
We are going to build a game of Tic Tac Toe using the Visual Basic language, using
the same skills that you just demonstrated by creating Macro1!
A spreadsheet is, in my opinion, one of the world’s greatest inventions. It lets you
do so many things. Calculations. Formulas. Organizing data. Creating reports. Charts.
The list is almost endless. It is also a great modeling tool—if you can imagine what
you need in terms of business or mathematical problem, you can develop a model
to build the answer. And when you apply the correct algorithm, the possibilities are
endless and the outcomes surprisingly impressive, given the amount of time you need
to spend. I will show you a few of these algorithms in this book. Hopefully this will
motivate your imagination to model and solve your own unique business, educational,
or recreational problems.
I want to show you how you can build a rudimentary game of Tic Tac Toe using
what you have learnt so far.
Let us say we want to use the cells in three columns and three rows of your spread
sheet to play the game. In the figure below, this is the green-shaded area:
FIGURE 2.11 Game area.
Let us say that you are playing the game with a friend and using the spreadsheet
to record your moves.
You are “X” and your friend is “O”.
As you can see, you have already won.
This simple code below will generate this win message for you.
Sub Macro1()
'
' Macro1 Macro
'
If Cells(1, 1) = "X" And Cells(2, 1) = "X" And Cells(3, 1) = "X" Then
MsgBox ("You win")
End If
End Sub
FIGURE 2.12 Win message code.